package com.ruoyi.algorithm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.algorithm.entity.TableStruct;
import com.ruoyi.algorithm.entity.UserTableStruct;
import com.ruoyi.algorithm.repository.TableStructRepository;
import com.ruoyi.algorithm.repository.UserTableStructRepository;
import com.ruoyi.algorithm.service.UserTableStructService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ：yanfa-03
 * @date ：Created in 2021/7/12/14:59
 * @description ：
 * @version: 1.0
 */
@Service
public class UserTableStructServiceImpl implements UserTableStructService {

    @Autowired
    private TableStructRepository tableStructRepository;

    @Autowired
    private UserTableStructRepository userTableStructRepository;

    /**
     * 更新表结构
     *
     * @param userId     用户ID
     * @param targetList 表结构列表
     * @return 是否成功
     */
    @Override
    public boolean updateTableStructByID(Long userId, List<TableStruct> targetList) {
        //update user_table_struct
        //make a empty List of user_table_struct
        ArrayList<UserTableStruct> userTableStructArrayList = new ArrayList<>();
        for (TableStruct tableStruct : targetList) {
            //get user_table_struct by id
            UserTableStruct uts = userTableStructRepository.getById(tableStruct.getId());
            if (ObjectUtils.isEmpty(uts)) {
                throw new RuntimeException("参数id有误，本次修改失败");
            }
            //set new variable(seq & display)
            uts.setSeq(tableStruct.getSeq());
            uts.setDisplay(tableStruct.getDisplay());
            //fill the utsList
            userTableStructArrayList.add(uts);
        }
        //update utsRepo
        return userTableStructRepository.updateBatchById(userTableStructArrayList, userTableStructArrayList.size());
    }

    /**
     * 给该用户增加所有表的对应关系表数据
     *
     * @param userId 用户ID
     */
    @Override
    public void insertByUserIdAndTableStructs(Long userId) {
        List<TableStruct> tableAllList = tableStructRepository.list();
        List<TableStruct> tableNameList = tableStructRepository.list(new QueryWrapper<TableStruct>()
                .select("DISTINCT table_name"));
        for (TableStruct tableStruct : tableNameList) {
            String tableName = tableStruct.getTableName();
            //构建分表名的列表
            ArrayList<TableStruct> tableStructs = new ArrayList<>();
            for (TableStruct struct : tableAllList) {
                if (struct.getTableName().equalsIgnoreCase(tableName)) {
                    tableStructs.add(struct);
                }
            }
            insertUserTableStruct(userId, tableStructs, tableAllList.size());
        }

    }

    /**
     * 根据tableStruct列表与用户ID新增关联表数据
     *
     * @param userId       用户ID
     * @param tableStructs tableStruct列表
     */
    private void insertUserTableStruct(Long userId, List<TableStruct> tableStructs, Integer size) {
        ArrayList<UserTableStruct> userTableStructs = new ArrayList<>();
        for (int i = 0; i < tableStructs.size(); i++) {
            TableStruct tableStruct = tableStructs.get(i);
            Long tableStructId = tableStruct.getId();
            String fieldKey = tableStruct.getFieldKey();
            if (fieldKey.contains("update") || fieldKey.contains("create") || fieldKey.equals("id") || fieldKey.equals("delFlag")) {
                userTableStructs.add(new UserTableStruct(userId, tableStructId, i + 1, false));
            } else {
                userTableStructs.add(new UserTableStruct(userId, tableStructId, i + 1, true));
            }
        }
        List<UserTableStruct> struts = userTableStructRepository.getListByUserId(userId);
        if (ObjectUtils.isEmpty(struts) || struts.size() != size) {
//            userTableStructRepository.remove(Wrappers.lambdaQuery(UserTableStruct.class).eq(UserTableStruct::getUserId, userId));
            userTableStructRepository.saveBatch(userTableStructs, userTableStructs.size());
        }
    }
}
